package net.esj.basic.utils.view;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

public class JavaTypeFormater {

	private static final Map FORMAT_MAP = new HashMap();
	static{
		FORMAT_MAP.put("int", Integer.class);
		FORMAT_MAP.put("long", Long.class);
		FORMAT_MAP.put("date", Date.class);
		FORMAT_MAP.put("datetime", Date.class);
		FORMAT_MAP.put("float", Float.class);
		FORMAT_MAP.put("double", Double.class);
		FORMAT_MAP.put("string", String.class);
	}
	
	private static final DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	
	public static final Object formate(String key,String value){
		Class<?> clazz = (Class<?>) FORMAT_MAP.get(key);
		if(clazz == null){
			return value;
		}
		if(clazz == Date.class){
			if(StringUtils.equals("datetime", key)){
				try {
					return timeFormat.parse(value);
				} catch (ParseException e) {
					e.printStackTrace();
					return value;
				}
			}else if(StringUtils.equals("date", key)){
				try {
					return dateFormat.parse(value);
				} catch (ParseException e) {
					e.printStackTrace();
					return value;
				}
			}else if(StringUtils.equals("string[]", key)){
				return value.split(",");
			}else if(StringUtils.equals("int[]", key)){
				String tmp[]  = value.split(",");
				int[] retal = new int[tmp.length];
				for(int i=0;i<tmp.length;i++){
					retal[i] = Integer.valueOf(tmp[i]);
				}
				return retal;
			}else{
				return value;
			}
		}else if(clazz == Integer.class){
			return Integer.valueOf(value);
		}else if(clazz == Float.class){
			return Float.valueOf(value);
		}else if(clazz == Double.class){
			return Double.valueOf(value);
		}else if(clazz == Long.class){
			return Long.valueOf(value);
		}
		return value;
	}
}
